// pages/cart/index.js
import {getSetting,chooseAddress,openSetting,showModal,showToast,requestPayment} from "../../utils/asyncWx.js";
import regeneratorRuntime, { async } from "../../libs/runtime/runtime";
import {request} from "../../request/index.js";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address:{},
    cart:[],
    totalPrice:0,
    totalNum:0
  },
  onShow(){
    //获取缓存中的收货地址信息
    const address=wx.getStorageSync("address");
    //获取缓存中 购物车数据
    let cart=wx.getStorageSync('cart')||[];
    cart=cart.filter(v=>v.checked);
    this.setData({
      address
    });
    let totalPrice=0;
    let totalNum=0;
    cart.forEach(v=>{
        totalNum+=v.num;
        totalPrice+=v.num*v.goods_price;
    })
    //给data赋值
    this.setData({
      cart,
      totalNum,
      totalPrice
    });

  }, 
  //点击支付
 async handlePrderPay(){
  try {
        //判断缓存中有没有token
        const token=wx.getStorageSync("token");
        //判断
        if(!token){
          wx.navigateTo({
            url: '/pages/auth/index',
          });
        }
        //创建订单
        // const header={Authorization:token};
        const order_price=this.data.totalPrice;
        const consignee_addr=this.data.address.all;
        const cart=this.data.cart;
        let goods=[];
        cart.forEach(v=>goods.push({
          goods_id:v.goods_id,
          goods_number:v.num,
          goods_price:v.goods_price
        }))
        //创建订单
        const orderParams={order_price,consignee_addr,goods};
        //准备发送请求 创建订单 获取订单编号
        const {order_number}=await request({url:"/my/orders/create",method:"POST",data:orderParams});
       //发起预支付接口
       const {pay}=await request({url:"/my/orders/req_unifiedorder",method:"POST",data:{order_number}});
       //发起微信支付
       //await requestPayment(pay);
       //查询后台订单状态
       const res =await request({url:"/my/orders/chkOrder",method:"POST",data:{order_number}});
       await showToast({title:"支付成功"})
       //删除已经支付的商品
       let newCart=wx.getStorageSync("cart");
       newCart=newCart.filter(v=>!v.checked);
       console.log(newCart);
       wx.setStorageSync("cart",newCart);
       //跳转到订单页面
        wx.navigateTo({
          url: '/pages/order/index'
        })

  } catch (error) {
    await showToast({title:"支付失败"})
  }
  }

})